<template>
  <ui-page class="container">
    <!-- table -->
    <ui-table v-bind="table.config" ref="table" class="content_container" :params="{tenantId: userInfo.tenantId}"
              @select-change="onSelectTableEntity">
      <!--   查询   -->
      <template v-slot:search-bar>
        <ui-table-select v-model="table.model.select" :reset="true">
          <ui-table-select-item name="name" label="部门名称" placeholder="请输入部门名称" show-label type="text"
                                :show-word-limit="false"/>
          <ui-table-select-item name="managerName" label="部门总经理" placeholder="请输入部门经理" show-label type="text"
                                :show-word-limit="false"/>
          <ui-table-select-item name="status" label="部门状态" placeholder="请选择部门状态" show-label
                                type="select" :data="depStatus" start-null/>
        </ui-table-select>
      </template>
      <!--   操作   -->
      <template v-slot:tool-bar>
        <el-button type="primary" icon="el-icon-plus" @click="handleEntityCreate">新增</el-button>
        <!--        <el-button type="primary" icon="el-icon-plus" @click="handleEntityDelete">删除</el-button>-->
<!--        <el-button type="primary" icon="el-icon-printer" @click="handleEntityExport">导出</el-button>-->
      </template>
      <ui-table-column label="序号" type="index" width="60px"/>
      <ui-table-column prop="name" label="部门名称"/>
      <ui-table-column prop="depManagerName" label="部门总经理"/>
      <ui-table-column prop="description" label="部门描述"/>
      <ui-table-column prop="statusText" label="部门状态">
        <template v-slot:default="{row}">
            <span :style="{color: row.statusText === '运营' ? 'green' : 'red'}">
              {{ row.statusText }}
            </span>
        </template>
      </ui-table-column>
      <ui-table-column type="action" :buttons="table.buttons" :resizable="false"/>
      <!--   分页   -->
      <template v-slot:footer-bar>
        <ui-table-pagination/>
      </template>
    </ui-table>
    <!-- form -->
    <ui-form-dialog ref="form" :title="form.title" :url="form.url" :loading="entityGetLoading"
                    :visible.sync="form.visible" class="entity-form" @after-submit="afterFormSubmit">
      <ui-form-item name="id" label="ID" type="hidden"/>
      <ui-form-item name="name" label="部门名称" type="text" vtype="required"/>
      <ui-form-item name="manager" label="部门总经理" type="select" :data="managerList" v-if="!form.isCreate"
                    :props="{ value: 'id', label: 'name' }" vtype="required"/>
<!--      <ui-form-item name="managerName" label="部门经理" type="hidden" v-if="!form.isCreate" vtype="required"/>-->
      <ui-form-item name="description" label="部门描述" type="text"/>
      <ui-form-item name="status" label="部门状态" type="select" :data="depStatus" vtype="required"/>
    </ui-form-dialog>
    <ui-form-dialog ref="detailForm" title="部门员工详情列表" :loading="entityGetLoading" disabled
                    :visible.sync="form.detailVisible" class="entity-form" width="1024px">
      <el-table :data="empList" style="width: 100%" stripe>
        <el-table-column label="序号" type="index" width="60px"/>
        <el-table-column prop="employeeId" label="员工编号" show-overflow-tooltip align="center"/>
        <el-table-column prop="name" label="员工姓名" show-overflow-tooltip align="center"/>
        <el-table-column prop="gender" label="员工性别" show-overflow-tooltip align="center">
          <template v-slot:default="{row}">
            <div style="display: flex;justify-content: center">
              {{ row.gender === 1 ? '男' : '女' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="positionText" label="职位" show-overflow-tooltip align="center"/>
        <el-table-column prop="phone" label="电话" show-overflow-tooltip align="center"/>
        <el-table-column prop="hireDate" label="入职时间" show-overflow-tooltip align="center"/>
        <el-table-column prop="address" label="住址" show-overflow-tooltip align="center"/>
        <el-table-column prop="status" label="在职状态" show-overflow-tooltip align="center">
          <template v-slot:default="{row}">
            <div :style="{color: row.status === 0 ? 'green' : 'red'}" style="display: flex; justify-content: center;">
              {{ row.status === 0 ? '在职' : '离职' }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </ui-form-dialog>
  </ui-page>
</template>
<script>
import {mapState} from 'vuex';
import to from "await-to-js";

const EntDepartment = {
  API: {
    create: '/Ent/EntDepartment/create',
    update: '/Ent/EntDepartment/update',
    delete: '/Ent/EntDepartment/delete',
    select: '/Ent/EntDepartment/select',
    export: '/Ent/EntDepartment/export',
    createList: '/Ent/EntDepartment/createList',
    updateList: '/Ent/EntDepartment/updateList',
    deleteList: '/Ent/EntDepartment/deleteList',
    selectList: '/Ent/EntDepartment/selectList',
    selectPage: '/Ent/EntDepartment/selectPage',
  },
  data() {
    return {
      api: EntDepartment.API,
      table: {
        config: {
          url: EntDepartment.API.selectPage,
        },
        model: {
          select: {},
        },
        buttons: [
          () => ({text: '修改', handle: this.handleEntityUpdateRow}),
          () => ({text: '删除', handle: this.handleEntityDeleteRow}),
          () => ({text: '详情', handle: this.handleEntityDetailRow}),
        ],
      },
      form: {
        isCreate: true,
        title: '新增',
        url: EntDepartment.API.create,
        visible: false,
        detailVisible: false,
        rules: {},
      },
      depStatus: [{value: 0, label: '运营'}, {value: 1, label: '非运营'}],
      managerList: [],
      empList: []
    };
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    onSelectTableEntity(selects) {
      if (selects.length <= 0) {
        return;
      }
      this.handleEntityUpdateRow(selects[selects.length - 1]);
    },
    handleEntityCreate() {
      this.form.isCreate = true;
      this.$refs.form.resetValues();
      this.form.title = '新增';
      this.form.url = this.api.create;
      this.form.visible = true;
    },
    handleEntityUpdate() {
      const sels = this.$refs.table.getSelection();
      if (sels.length !== 1) {
        this.$message.info('请选择要修改的数据');
        return;
      }
      this.handleEntityUpdateRow(sels[0]);
    },
    handleEntityDelete() {
      const sels = this.$refs.table.getSelection();
      if (sels.length <= 0) {
        this.$message.info('请选择要删除的数据');
        return;
      }
      this.deleteEntities(sels.map(item => item.id)).then(({success}) => {
        if (!success) {
          return;
        }
        this.reloadTable();
      });
    },
    handleEntityUpdateRow(row) {
      this.form.isCreate = false;
      this.form.title = '修改';
      this.form.url = this.api.update;
      this.getManager(row.id)
      this.$nextTick (() => {
        this.form.visible = true;

        this.selectEntity(row.id).then(({success, data}) => {
          if (!success) {
            this.form.visible = false;
            return;
          }
          if (data.depManagerName === null) {
            data.manager = null
            data.managerName = null
          }
          console.log(data)
          this.$refs.form.resetValues(data);
        });
      })
    },
    // 详情
    handleEntityDetailRow(row) {
      this.getManager(row.id)
      this.form.detailVisible = true;
    },
    handleEntityDeleteRow(row) {
      this.getManager(row.id).then(() => {
        if (this.managerList.length > 0) {
          this.$message.error('删除失败！该部门下存在员工');
          return
        }
        this.deleteEntity(row.id).then(({success}) => {
          if (!success) {
            return;
          }
          this.reloadTable();
        });
      })
    },
    async handleEntityExport() {
      const loading = this.$loading({text: '数据加载中..'});
      const url = this.api.export;
      await this.$refs.table.exportEntity(url, '导出.xls');
      loading.close();
    },
    reloadTable() {
      this.$refs.table && this.$refs.table.reload();
    },
    afterFormSubmit({success}) {
      if (!success) {
        return;
      }
      this.form.visible = false;
      this.reloadTable();
    },
    async getManager (depId) {
      const tenantId = this.userInfo.tenantId
      const [, result] = await to(
          this.$axios.get(
              `/Ent/EntEmployee/selectList?depId=${depId}&tenantId=${tenantId}&status=0&position=2`))
      this.managerList = result.data || []
      console.log(this.managerList)
      const [, result2] = await to(
          this.$axios.get(
              `/Ent/EntEmployee/selectList?depId=${depId}&tenantId=${tenantId}`))
      this.empList = result2.data || []
    },
  },
};
export default EntDepartment;
</script>
<style lang="less" scoped>
</style>
